/**
 * 
 */
package com.spring.mvc.util;

import java.security.MessageDigest;
import java.util.Random;

public class Encode {

	/**
	 * 将给定字符串MD5加密
	 * @param str
	 * @return
	 */
	public static final String encode(String str) {
		try {
			byte strtemp[] = str.getBytes();
			MessageDigest mdtemp = MessageDigest.getInstance("MD5");
			mdtemp.update(strtemp);
			byte md[] = mdtemp.digest();
			return byteToHEX(md);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 将byte数组转换为16进制字符串
	 * @param bytes
	 * @return
	 */
	private static String byteToHEX(byte bytes[]) {
		char Digit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		StringBuffer sb = new StringBuffer();
		char ob[] = new char[2];
		for (int i = 0; i < bytes.length; i++) {
			byte byte0 = bytes[i];
			ob[0] = Digit[byte0 >>> 4 & 0xf];
			ob[1] = Digit[byte0 & 0xf];
			sb.append(ob);
		}

		return sb.toString();
	}

	/**
	 * 随机生成6位验证码
	 * @return
	 */
	public static String getMobileActiveCode() {
		String sRand = "";
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
		}
		return sRand;
	}

	public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}
}
